import { Button, Collapse } from "antd";
import { Link } from "react-router";
import { Component, type PropsWithChildren } from "react";

export default class ErrorBoundary extends Component<
  PropsWithChildren,
  { error: any }
> {
  override state = {
    error: null as any,
  };

  constructor(props: PropsWithChildren) {
    super(props);
  }

  static getDerivedStateFromError(error: any) {
    // Update state so the next render will show the fallback UI.

    return { error: error };
  }

  override render() {
    const { error } = this.state;
    if (error) {
      return (
        <div className="pt-32 text-center text-sm">
          <p className="my-2">似乎遇到了不可恢复的问题，请尝试刷新页面。</p>
          <p className="my-2">若问题一直持续存在，请尝试联系管理人员。</p>
          <p className="mt-8">
            <Link to="/">
              <Button type="primary">回到首页</Button>
            </Link>
          </p>
          <Collapse
            bordered={false}
            style={{ background: "transparent" }}
            items={[
              {
                key: "1",
                label: "详细信息",
                children: (
                  <div className="rounded bg-red-200 p-2 text-left text-red-500">
                    <p className="font-bold">{error.message}</p>
                    {error instanceof Error && <p>{error.stack}</p>}
                  </div>
                ),
                showArrow: false,
              },
            ]}
          />
        </div>
      );
    }

    return this.props.children;
  }
}
